package com.example.cadmin.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.cadmin.entity.MyDept;
import com.example.cadmin.entity.MyRoleUser;
import com.example.cadmin.entity.MyUser;
import com.example.cadmin.entityVo.MyDeptTreeVo;
import com.example.cadmin.entityVo.MyUserVo;
import com.example.cadmin.mapper.MyDeptMapper;
import com.example.cadmin.mapper.MyRoleUserMapper;
import com.example.cadmin.mapper.MyUserMapper;
import com.example.cadmin.utils.DateFormat;
import com.example.cadmin.utils.ResponseModel;
import com.example.cadmin.utils.TreeUtil;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author zzsoft
 * @since 2023-01-07
 */
@Service
public class MyUserService extends ServiceImpl<MyUserMapper, MyUser> {
    @Resource
    private MyUserMapper myUserMapper;
    @Resource
    private MyRoleUserMapper myRoleUserMapper;
    @Resource
    private MyDeptMapper myDeptMapper;

    /**
     * 绘制用户树
     */
    public Map<String, Object> buildDept() {
        List<MyDeptTreeVo> myDeptTreeVoList = myDeptMapper.buildDept();
        List<MyDeptTreeVo> resultList = TreeUtil.buildDeptAll(myDeptTreeVoList);
        Map<String, Object> map = new HashMap<>();
        map.put("code", 200);
        map.put("message", 200);
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("status", map);
        resultMap.put("data", resultList);
        return resultMap;

    }

    /*
    获取用户列表
     */
    public Map<String, Object> userList(String user_name, String nick_name, String deptId, int page, int limit) {
        Map<String, Object> map = new HashMap<>();
        map.put("code", 0);
        map.put("msg", "数据请求成功");
        Map<String, Object> paramsMap = new HashMap<>();
        // 手动处理分页
        int offset = (page - 1) * limit;
        paramsMap.put("page", offset);
        paramsMap.put("limit", limit);
        if (StrUtil.isEmpty(deptId)) {
            if (StrUtil.isNotEmpty(user_name)) {
                paramsMap.put("user_name", user_name);
            }
            if (StrUtil.isNotEmpty(nick_name)) {
                paramsMap.put("nick_name", nick_name);
            }
            List<Map<String, Object>> mapList = myUserMapper.getAllUser(paramsMap);
            map.put("count", myUserMapper.getAllUserCount(paramsMap));
            map.put("data", mapList);
        } else {
            paramsMap.put("deptId", deptId);
            List<Map<String, Object>> mapList = myUserMapper.getDeptUser(paramsMap);
            map.put("data", mapList);
            map.put("count", myUserMapper.getDeptUserCount(deptId));
        }
        return map;
    }

    /*
    通过用户名判断用户是否存在
     */
    public MyUser checkUserExists(String userName) {
        return myUserMapper.checkUserExists(userName);
    }

    /*
    新增用户
     */
    public ResponseModel saveUser(JSONObject data) {
        // 添加用户信息
        MyUser myUserVo = new MyUser();

        myUserVo.setUserName(data.getStr("userName"));
        myUserVo.setNickName(data.getStr("nickName"));
        myUserVo.setDeptId(data.getInt("deptId"));
        if (StrUtil.isNotEmpty(data.getStr("password"))) {
            BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
            myUserVo.setPassword(bCryptPasswordEncoder.encode(data.getStr("password")));
        }
        myUserVo.setPhone(data.getStr("phone"));
        if (data.getInt("status") == 1) {
            myUserVo.setStatus(true);
        }else {
            myUserVo.setStatus(false);
        }
        myUserVo.setCreateTime(DateFormat.getTime());
        myUserVo.setUpdateTime(DateFormat.getTime());
        if (data.getInt("roleId") == 1) {
            myUserVo.setUserType(1);
        }else {
            myUserVo.setUserType(2);
        }
        int status = myUserMapper.insert(myUserVo);
        if (status > 0) {
            // 添加用户和角色表依赖
            MyRoleUser myRoleUser = new MyRoleUser();
            myRoleUser.setRoleId(data.getInt("roleId"));
            myRoleUser.setUserId(myUserVo.getUserId());
            myRoleUserMapper.save(myRoleUser);
            return ResponseModel.success("用户添加成功");
        } else {
            return ResponseModel.fail("用户添加失败");
        }
    }

    /*
    通过id返回对应数据
     */
    public ModelAndView editView(String userId) {
        ModelAndView modelAndView = new ModelAndView();
        Map<String, Object> myUser = myUserMapper.getUser(userId);
        modelAndView.addAllObjects(myUser);
        modelAndView.setViewName("user/user-edit");
        List<MyDept> myDeptList = myDeptMapper.selectList(new QueryWrapper<MyDept>().eq("status", 1).orderByAsc("sort"));
        modelAndView.addObject("myDeptList", myDeptList);
        return modelAndView;
    }

    /*
    执行用户数据修改
     */
    public ResponseModel editUser(JSONObject data) {
        //1.先修改用户信息
        data.set("user_id", data.getInt("user_id"));
        data.set("update_time", DateUtil.now());
        data.set("status", data.getBool("status"));
        if (StrUtil.isNotEmpty(data.getStr("password"))) {
            BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
            data.set("password", bCryptPasswordEncoder.encode(data.getStr("password")));
        }
        myUserMapper.updateUser(data);
        //2.修改角色信息
        MyRoleUser myRoleUser = new MyRoleUser();
        myRoleUser.setUserId(data.getInt("user_id"));
        myRoleUser.setRoleId(data.getInt("roleId"));
        myRoleUserMapper.updateById(myRoleUser);
        return ResponseModel.success("修改用户成功");
    }

    /*
    删除用户
     */
    public ResponseModel deleteUser(String user_id) {
        String[] strings = user_id.split(",");
        List<String> idList = CollUtil.newArrayList(strings);
        int delCount = myUserMapper.deleteBatchIds(idList);
        if (delCount > 0) {
            return ResponseModel.success("删除成功");
        } else {
            return ResponseModel.fail("删除失败,请重新尝试");
        }
    }

    /*
    修改用户状态
     */
    public ResponseModel changeStatus(JSONObject data) {
        UpdateWrapper<MyUser> myUserUpdateWrapper = new UpdateWrapper<>();
        //条件构造器Set方法
        //假设只更新一个字段在使用updateWrapper 的构造器中也需要构造一个实体对象,这样比较麻烦。可以使用updateWrapper的set方法
        myUserUpdateWrapper.eq("user_id", data.getInt("userId")).set("status", data.getBool("status"));
//        MyUser myUser = new MyUser();
//        myUser.setStatus(data.getBool("status"));
        int count = myUserMapper.update(null, myUserUpdateWrapper);
        if (count > 0) {
            if (data.getInt("status") == 0) {
                return ResponseModel.success("禁用成功");
            } else {
                return ResponseModel.success("启用成功");
            }
        } else {
            return ResponseModel.fail("请求失败");
        }
    }

    /*
        根据用户名获取用户
     */
    public MyUser getUserByName(String userName) {
        return myUserMapper.getUserByName(userName);
    }

    /*
    根据id获取用户
     */
    public MyUser getUser(String id) {

        return myUserMapper.getUserPwd(id);
    }

    /*
        执行密码更新操作
     */
    public int changePwd(MyUser myUser) {
        return myUserMapper.updateById(myUser);
    }
}
